package com.hxm.meizi.ui.fragment;

import android.animation.LayoutTransition;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.utils.LogUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.hxm.meizi.R;
import com.hxm.meizi.app.Constants;
import com.hxm.meizi.entity.EveryDay;
import com.hxm.meizi.entity.ImageInfo;
import com.hxm.meizi.entity.ZhuanTi;
import com.hxm.meizi.entity.ZhuanTiName;
import com.hxm.meizi.entity.ZiPaiImage;
import com.hxm.meizi.http.JsoupDoc;
import com.hxm.meizi.listener.ItemsRequestListener;
import com.hxm.meizi.listener.OnItemClickListener;
import com.hxm.meizi.provider.AllProvider;
import com.hxm.meizi.provider.ImageProvider;
import com.hxm.meizi.provider.ZhuanNameProvider;
import com.hxm.meizi.provider.ZhuanTiProvider;
import com.hxm.meizi.provider.ZiPaiProvider;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.concurrent.TimeUnit;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Created by hxm on 2017/2/18.
 * balala
 */

public class ImageFragment extends Fragment {
    public static final String TAG = "ImageFragment";
    private String imageKey;
    private TwinklingRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private MultiTypeAdapter adapter;
    private RelativeLayout linear;
    private TextView tvNetState;
    private ImageView progressBar;

    public static ImageFragment newInstance(String type) {
        Bundle args = new Bundle();
        args.putString("key", type);
        ImageFragment fragment = new ImageFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imageKey = getArguments().getString("key");
        Log.i(TAG, "onCreate: " + imageKey);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_image, container, false);
        initView(view);
        initData();
        return view;
    }

    private void initView(View view) {
        linear = (RelativeLayout) view.findViewById(R.id.linear);
        tvNetState = (TextView) view.findViewById(R.id.tv_net_state);
        progressBar = (ImageView) view.findViewById(R.id.progress_bar);
        LayoutTransition transition = new LayoutTransition();
        transition.setDuration(500);
        linear.setLayoutTransition(new LayoutTransition());
        refreshLayout = (TwinklingRefreshLayout) view.findViewById(R.id.refresh_layout);
        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                Observable.timer(1000, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<Long>() {
                            @Override
                            public void call(Long aLong) {
                                ToastUtils.showShortToast("还没有实现");
                                refreshLayout.finishRefreshing();
                            }
                        });
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                Observable.timer(1000, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<Long>() {
                            @Override
                            public void call(Long aLong) {
                                ToastUtils.showShortToast("还没有实现");
                                refreshLayout.finishLoadmore();
                            }
                        });
            }
        });
    }

    private void initData() {
        JsoupDoc.getImageList(imageKey, new ItemsRequestListener(progressBar) {
            @Override
            public void onSuccess(Items items) {
                super.onSuccess(items);
                adapter = new MultiTypeAdapter(items);
                adapter.register(ImageInfo.class, new ImageProvider(new OnItemClickListener() {
                    @Override
                    public void click(String url) {
                        ImageDetailFragment fragment = ImageDetailFragment.newInstance(url);
                        LogUtils.i(TAG, url);
                        addFragment(url, fragment);
                    }
                }));
                adapter.register(ZiPaiImage.class, new ZiPaiProvider());
                adapter.register(ZhuanTiName.class, new ZhuanNameProvider());
                adapter.register(EveryDay.class, new AllProvider(new OnItemClickListener() {
                    @Override
                    public void click(String url) {
                        ImageDetailFragment fragment = ImageDetailFragment.newInstance(url);
                        LogUtils.i(TAG, url);
                        addFragment(url, fragment);
                    }
                }));
                adapter.register(ZhuanTi.class, new ZhuanTiProvider(new ZhuanTiProvider.OnZhuanTiClickListener() {
                    @Override
                    public void onClick(String url) {
                        ImageFragment fragment = ImageFragment.newInstance(url);
                        addFragment(url, fragment);
                    }
                }));
                if (imageKey.equals(Constants.ZHUAN_TI)) {
                    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
                } else {
                    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
                }
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(String reason) {
                super.onFailure(reason);
                LogUtils.i(TAG, reason);
                tvNetState.setText(reason);
                tvNetState.setVisibility(View.VISIBLE);
                Observable.timer(2500, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<Long>() {
                            @Override
                            public void call(Long aLong) {
                                tvNetState.setVisibility(View.GONE);
                            }
                        });
            }
        });
    }

    private void addFragment(String url, Fragment fragment) {
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        transaction.add(R.id.container, fragment, url);
        transaction.addToBackStack(url);
        transaction.commit();
    }
}
